<template>
  <div class="kgArchives flex">
    <div class="archives-sider">
      <search-comp
        :entityObj="entityObj"
        :isArchives="true"
        @handleSearch="handleSearch"
      ></search-comp>
      <div class="archives-sider-body">
        <div class="archives-sider-header flex">
          <div class="sidebar-header-record">
            <span>{{ total }}</span> 记录 /
            <span>{{ checkEntityList.length }}</span> 选中
          </div>
          <el-pagination
            v-model:current-page="entityObj.current"
            :background="false"
            :pager-count="5"
            :total="total"
            layout=" prev, pager, next"
            small
            @current-change="handleCurrentChange"
          />
        </div>
        <div class="archives-sider-content">
          <el-scrollbar v-if="entityList.length">
            <div
              v-for="archive in entityList"
              :key="archive.vid"
              :class="currentEntity.vid === archive.vid ? 'active' : ''"
              class="archives-sider-item cursor-pointer"
              @click="handleArchiveClick(archive)"
            >
              <div class="sidebar-item-left">
                <div :title="archive.name" class="sidebar-item-left-name">
                  {{ archive.name }}
                </div>
                <div class="sidebar-item-left-classify">
                  <span>所属分类：</span>{{ archive.entityTypeName }}
                </div>
                <div class="sidebar-item-left-entity">
                  <span>所属本体：</span>{{ archive.entityTypeName }}
                </div>
              </div>
              <div class="sidebar-item-right">
                <el-checkbox
                  :model-value="archive.isCheck"
                  size="large"
                  @click.prevent="handleClickSelect($event, archive)"
                />
              </div>
            </div>
          </el-scrollbar>
          <empty-comp v-else></empty-comp>
        </div>
      </div>
      <div class="archives-sider-footer flex justify-between items-center">
        <el-checkbox
          :disabled="!!!+entityList.length"
          :model-value="currentCheckAllCmp"
          class="mr-0"
          label="当前页全选"
          @change="handleCurrentCheck"
        />
        <el-button
          :disabled="!checkEntityList.length"
          type="primary"
          @click="handleLinkAnalyse"
          >导入关联分析
        </el-button>
      </div>
    </div>
    <div class="archives-container flex flex-col flex-1">
      <div v-if="!isEmpty(currentEntity)" class="archives-container-tab">
        <el-carousel
          ref="carouselRef"
          :autoplay="false"
          :loop="false"
          arrow="always"
          indicator-position="none"
        >
          <el-carousel-item
            v-for="(tabL, index) in tabCompList"
            :key="index"
            style="height: 64px"
          >
            <div class="tab flex">
              <div
                v-for="tab in tabL"
                :key="tab.id"
                :class="tab.vid === currentEntity.vid ? 'active' : ''"
                class="tab-item flex cursor-pointer"
                @click="handleTabClick(tab)"
              >
                <div :title="tab.name" class="name">{{ tab.name }}</div>
                <i
                  class="iconfont icon_close cursor-pointer"
                  @click.stop="handleDeleteTab(tab)"
                ></i>
              </div>
            </div>
          </el-carousel-item>
        </el-carousel>
      </div>
      <div
        v-if="!isEmpty(currentEntity)"
        class="archives-container-detail flex-1 w-full bg-white mt-4"
      >
        <div class="archives-container-detail-header flex justify-between">
          <div class="text">详情</div>
          <div class="detail-icon mr-20">
            <i
              class="iconfont icon_share_fil cursor-pointer"
              @click="handleShare"
            ></i>
          </div>
        </div>
        <div class="archives-container-detail-body">
          <div class="detail-body-top flex mt-[24px] mb-[28px]">
            <div
              :style="{ backgroundColor: currentEntity.backgroundColor }"
              class="w-[88px] h-[88px] rounded-full mr-[32px] flex justify-center items-center"
            >
              <i
                :class="currentEntity.icon"
                class="text-white !text-[40px] iconfont"
              ></i>
            </div>
            <div class="archives-sider-detail-item">
              <div class="sidebar-item-left">
                <div
                  class="sidebar-item-left-name"
                  style="
                    max-width: 800px;
                    overflow: inherit;
                    white-space: pre-wrap;
                  "
                >
                  {{ currentEntity.name }}
                </div>
                <div class="sidebar-item-left-classify">
                  <span>所属分类：</span>{{ currentEntity.entityTypeName }}
                </div>
                <div class="sidebar-item-left-entity">
                  <span>所属本体：</span>{{ currentEntity.entityTypeName }}
                </div>
              </div>
            </div>
          </div>
          <ul class="detail-body-content max-h-[540px] overflow-y-auto">
            <li class="detail-body-content-prop flex bg-[#F7F8FA]">
              <div class="propName">属性名</div>
              <div class="propValue flex-1">属性值</div>
            </li>
            <li
              v-for="item in currentEntity.entityAttrList"
              :key="item.code"
              class="detail-body-content-prop flex"
              style="border-bottom: 1px solid #edeff4"
            >
              <div class="propName">{{ item.name }}</div>
              <div class="propValue flex-1">{{ item.value }}</div>
            </li>
          </ul>
        </div>
      </div>
      <div v-else class="w-full h-full bg-white">
        <empty-comp></empty-comp>
      </div>
    </div>
    <ShareDialogNew
      :visible="shareVisibel"
      @handleShareClose="handleShareClose"
      @handleShareKg="handleShareKg"
    ></ShareDialogNew>
  </div>
</template>

<script lang="ts" setup>
import { useRoute, useRouter } from "vue-router";
import SearchComp from "@/views/kgKnowledgePortal/search-comp.vue";
import {
  entityListApi,
  kgShareApi,
  entityDetailApi,
  LinkAnalyseApi,
} from "@/api/kgKnowledgePortal/index";
import ShareDialogNew from "./components/ShareDialogNew.vue";
import { ElMessage } from "element-plus";
import { isEmpty } from "lodash-es";

const route = useRoute();
const router = useRouter();

export interface EntityObjInterFace {
  entityType: string;
  name: string;
  comEntityAttr: { sysType: string };
  entityAttrList: Array<any>;
  current?: number;
  size?: number;
  vid?: string;
}

let entityObj = reactive<EntityObjInterFace>({
  entityType: "",
  name: "",
  comEntityAttr: { sysType: "1" },
  entityAttrList: [],
  current: 1,
  size: 10,
  vid: "",
});

/**
 * 针对列表的处理
 * */
const entityList = ref([]);
const total = ref(0);
const currentEntity: Ref<any> = ref({});
const tabList = ref([]);

onMounted(async () => {
  //在从门户跳转过来时
  if (route.query.comEntityAttr) {
    entityObj.comEntityAttr.sysType = route.query.comEntityAttr as string;
    entityObj.entityType = route.query.entityType as string;
    entityObj.name = route.query.name as string;
    entityObj.entityAttrList = JSON.parse(route.query.entityAttrList as string);
    await getEntityList();
  } else if (route.query.vid) {
    await getEntityDetail(route.query.vid);
  } else {
    await getEntityList();
  }
  //如果有数据，把第一个数据默认展示
  if (entityList.value.length && entityObj.current === 1) {
    currentEntity.value = entityList.value[0];
    tabList.value.push(currentEntity.value);
  }
});
//从分享页面跳转，查询详情
const getEntityDetail = async (vid) => {
  const { code, data } = await entityDetailApi({ vid });
  if (code === 200) {
    entityList.value = [data];
    total.value = entityList.value.length;
  }
};

const getEntityList = async () => {
  let { code, data } = await entityListApi(entityObj);
  try {
    if (code === 200) {
      entityList.value = data.records.map((item) => {
        let flag = false;
        if (checkEntityList.value.includes(item.vid)) {
          flag = true;
        }
        return {
          ...item,
          isCheck: flag,
        };
      });

      total.value = data.total;
    } else {
      entityList.value = [];
      total.value = 0;
    }
  } catch {
    entityList.value = [];
    total.value = 0;
  }
};
//分页
const handleCurrentChange = (val: number) => {
  entityObj.current = val;
  getEntityList();
};
/**
 * 搜索部分
 */
const handleSearch = async (query) => {
  checkEntityList.value = [];
  tabList.value = [];
  currentEntity.value = {};
  entityObj.entityType = query.entityType;
  entityObj.name = query.name;
  entityObj.entityAttrList = JSON.parse(query.entityAttrList);
  entityObj.comEntityAttr.sysType = query.comEntityAttr;
  entityObj.current = 1;
  await getEntityList();
  //如果有数据，把第一个数据默认展示
  if (entityList.value.length && entityObj.current === 1) {
    currentEntity.value = entityList.value[0];
    tabList.value.push(currentEntity.value);
  }
};
//计算当前页选择问题
const currentCheckAllCmp = computed(() => {
  if (!entityList.value.length) return false;
  return entityList.value.every((item) => {
    return item.isCheck;
  });
});
const handleCurrentCheck = (val) => {
  if (val) {
    entityList.value = entityList.value.map((item) => {
      if (!checkEntityList.value.includes(item.vid)) {
        // 回显数据里没有本条，把这条加进来(选中)
        checkEntityList.value.push(item.vid);
      }
      item.isCheck = true;
      return item;
    });
  } else {
    entityList.value = entityList.value.map((item) => {
      checkEntityList.value.forEach((vid, index) => {
        if (vid === item.vid) {
          checkEntityList.value.splice(index, 1);
        }
      });
      item.isCheck = false;
      return item;
    });
  }
};

//计算选中状态
const checkEntityList = ref([]);

const handleClickSelect = (e, archive) => {
  e.stopPropagation();
  if (!checkEntityList.value.includes(archive.vid)) {
    // 回显数据里没有本条，把这条加进来(选中)
    checkEntityList.value.push(archive.vid);
    archive.isCheck = true;
  } else {
    // 回显数据里有本条，把这条删除(取消选中)
    checkEntityList.value.forEach((vid, index) => {
      if (vid === archive.vid) {
        checkEntityList.value.splice(index, 1);
        archive.isCheck = false;
      }
    });
  }
};

//计算tab的添加
const carouselRef = ref();
const handleArchiveClick = (item) => {
  if (item.vid === currentEntity.value.vid) {
    nextTick(() => {
      findCarouselIndex(item);
    });
    return;
  }
  currentEntity.value = item;
  let flag = tabList.value.find((tab) => {
    return tab.vid === item.vid;
  });
  if (flag) {
    nextTick(() => {
      handleArchiveClick(item);
    });

    return;
  }
  tabList.value.push(item);
  nextTick(() => {
    findCarouselIndex(item);
  });
};
const findCarouselIndex = (item) => {
  let index = tabList.value.findIndex((tab) => {
    return tab.vid === item.vid;
  });
  if (index == -1) return;
  let currentCarouseIndex = Math.floor(index / 7);
  carouselRef.value.setActiveItem(currentCarouseIndex);
};

const handleDeleteTab = (tab) => {
  if (tab.vid === currentEntity.value.vid) {
    let tabIndex = tabList.value.findIndex((item) => {
      return tab.vid === item.vid;
    });
    tabList.value.splice(tabIndex, 1);

    if (tabList.value.length) {
      currentEntity.value = tabList.value[tabList.value.length - 1];
    } else {
      currentEntity.value = {};
    }
  } else {
    let tabIndex = tabList.value.findIndex((item) => {
      return tab.vid === item.vid;
    });
    tabList.value.splice(tabIndex, 1);
  }
};

const tabCompList = computed(() => {
  return group(tabList.value, 7);
});

/**
 * 数组拆分
 * */
const group = (array, subGroupLength) => {
  if (!array?.length) return [];
  let index = 0;
  let newArray = [];
  while (index < array.length) {
    newArray.push(array.slice(index, (index += subGroupLength)));
  }
  return newArray;
};

const handleTabClick = (tab) => {
  currentEntity.value = tab;
};

const getSysName = (tags) => {
  let sysName = "";
  tags.forEach((item) => {
    if (item.properties.sys_name) {
      sysName = item.properties.sys_name;
    }
  });
  return sysName;
};
/**
 * 导入关联分析
 */
import { useCanvasStoreHook } from "@/stores/modules/canvas";

const useCanvasStore = useCanvasStoreHook();
const handleLinkAnalyse = async () => {
  let tagsId = checkEntityList.value.join(",");
  let { code, data } = await LinkAnalyseApi({ tagsId: tagsId });
  if (code === 200) {
    let tagsData = data.map((item) => {
      item.id = item.vid;
      item.label = getSysName(item.tags);
      return item;
    });
    let uuid = `${Date.now()}`;
    useCanvasStore.pushCanvas({
      uuid,
      name: `临时文件${uuid}`,
      data: {
        nodes: [],
        edges: [],
      },
    });
    useCanvasStore.setCanvasData(tagsData);
    router.push("/associationAnalysis/canvas/index");
  }
};

/**
 *
 * 弹窗分享
 */
const shareVisibel = ref(false);
const handleShare = () => {
  shareVisibel.value = true;
};
const handleShareKg = async (userIdList) => {
  let params = {
    vid: currentEntity.value.vid,
    name: currentEntity.value.name,
    userIdList: userIdList,
  };
  try {
    let { code, msg } = await kgShareApi(params);
    if (code === 200) {
      ElMessage.success("分享成功");
    } else {
      ElMessage.error(msg);
    }
    shareVisibel.value = false;
  } catch (error) {
    ElMessage.error(error);
    shareVisibel.value = false;
  }
};
const handleShareClose = () => {
  shareVisibel.value = false;
};
</script>

<style lang="scss" scoped>
.kgArchives {
  position: absolute;
  top: 0;
  width: 100%;
  height: 100%;
  margin: 0 !important;
}

.archives-sider {
  position: relative;
  display: flex;
  flex-direction: column;
  width: 355px;
  height: 100%;
  padding: 16px 8px 0;
  background: #fff;

  & ::v-deep .kg-header-search {
    margin-top: 0;
  }

  .archives-sider-header {
    margin: 16px 0;

    .sidebar-header-record {
      margin-right: 10px;
      font-size: 14px;

      span {
        color: #2b1dff;
      }
    }
  }

  .archives-sider-body {
    position: relative;
    display: flex;
    flex: 1;
    flex-direction: column;
    overflow: hidden;

    .archives-sider-content {
      flex: 1;
      margin-bottom: 48px;
      overflow-y: auto;
    }
  }

  .archives-sider-footer {
    position: absolute;
    bottom: 0;
    left: 0;
    z-index: 2;
    width: 355px;
    height: 48px;
    padding: 0 20px;
    background: #fff;
    border: 1px solid #edeff4;
  }

  .archives-sider-item {
    display: flex;
    justify-content: space-between;
    height: 120px;
    padding: 16px;
    margin: 10px 0;
    color: #222;
    background: #fff;
    border: 1px solid #bfbfbf;
    border-radius: 4px;

    &:hover {
      border: 1px solid #2b1dff;
      box-shadow: inset 3px 0 0 0 #2b1dff;
    }
  }

  .archives-sider-item.active {
    border: 1px solid #2b1dff;
    box-shadow: inset 3px 0 0 0 #2b1dff;
  }
}

.sidebar-item-left-name {
  max-width: 280px;
  overflow: hidden;
  font-size: 16px;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.sidebar-item-left-classify,
.sidebar-item-left-entity {
  font-size: 12px;
  font-weight: 400;

  span {
    color: #7f8a9b;
  }
}

.sidebar-item-left-classify {
  margin: 16px 0 8px;
}

.archives-container {
  padding: 17px;

  .archives-container-tab {
    width: 100%;
    height: 64px;
    background: rgb(255 255 255);

    ::v-deep .el-carousel__container {
      height: 64px;

      .el-carousel__arrow {
        background: rgb(255 255 255);
        box-shadow: rgb(13 22 50 / 10%) 0 2px 8px 0;

        .el-icon {
          color: #99a3b8;
        }
      }

      .tab {
        padding: 16px 44px;
      }

      .tab-item.active {
        color: #fff;
        background: #2b1dff;
      }

      .tab-item {
        width: 177px;
        height: 32px;
        padding: 0 4px;
        margin: 0 15px;
        line-height: 32px;
        color: #7f8a9b;
        background: #f7f8fa;
        border-radius: 4px;

        &:hover {
          color: #fff;
          background: #2b1dff;
        }

        .name {
          width: 145px;
          overflow: hidden; /* 溢出隐藏 */
          font-size: 14px;
          text-overflow: ellipsis; /* 溢出显示省略号 */
          white-space: nowrap; /* 强制不换行 */
        }
      }
    }
  }

  .archives-container-detail {
    padding: 0 24px;

    .archives-container-detail-header {
      line-height: 58px;
      border-bottom: 1px solid #edeff4;

      .icon_share_fil {
        &:hover {
          color: #2b1dff;
        }
      }

      .text {
        position: relative;
        margin-left: 10px;
        font-size: 18px;
        font-weight: bold;
        color: #2b1dff;

        &::before {
          position: absolute;
          top: 22px;
          left: -10px;
          width: 3px;
          height: 16px;
          content: "";
          background: #2b1dff;
        }
      }
    }

    .detail-body-content-prop {
      font-size: 14px;
      line-height: 48px;

      .propName {
        width: 144px;
        padding-left: 10px;
      }
    }
  }
}
</style>
